package com.yonyou.pmclouds.openapi.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.conf.OpenApiProperties;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.util.ChineseStringUtils;
import com.yonyou.pmclouds.outter.enterprise.EnterpriseInfoQuery;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.team.entity.TeamEnterpriseVO;
import com.yonyou.pmclouds.team.entity.TeamEnterpriseViewVO;
import com.yonyou.pmclouds.team.entity.TeamMemberViewVO;
import com.yonyou.pmclouds.team.rmiitf.TeamEnterOpenQuery;
import com.yonyou.pmclouds.team.rmiitf.TeamMemberMaintain;
import com.yonyou.pmclouds.team.rmiitf.TeamMemberQuery;
import com.yonyou.pmclouds.user.entity.UserInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/openapi/project")
public class ProjectOpenController {
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private TeamMemberQuery memberQuery;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private TeamMemberMaintain memberMaintain;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private TeamEnterOpenQuery enterpriseQuery;
    @Autowired
    private UserInfoQuery userInfoQuery;
    @Autowired
    private EnterpriseInfoQuery enterpriseInfoQuery;
    @Autowired
    private OpenApiProperties openApiProp;

    @RequestMapping("/getTeamInfo")
    @ResponseBody
    public TeamInfoResultVO getEnterpriseOfProject(@RequestBody TeamInfoRequestParam requestParam) throws BusinessException {

        log.info("外部参数-->pkTenant:"+requestParam.getPkTenant()+",pkProject:"+requestParam.getPkProject());
        if(StringUtils.isEmpty(requestParam.getPkTenant()) || StringUtils.isEmpty(requestParam.getPkProject()))
            return new TeamInfoResultVO();
        if(!ArrayUtils.contains(openApiProp.getTenantInfos(),requestParam.getPkTenant()) )
            throw new BusinessException("租户："+requestParam.getPkTenant()+"没有访问openapi的权限，请联系管理员");

        TeamEnterpriseViewVO[] result = enterpriseQuery.getTeamInfoByProject(requestParam.getPkTenant(),requestParam.getPkProject());
        //设置参与企业名称
        enterpriseInfoQuery.tranEntInfoField(result, new String[]{TeamEnterpriseVO.PK_ENTERPRISE},
                new String[]{TeamEnterpriseVO.ENTERPRISE_NAME});
        TeamInfoResultVO resultVO = new TeamInfoResultVO();
        resultVO.setPkProject(requestParam.getPkProject());
        resultVO.setPkTenant(requestParam.getPkTenant());
        if (ArrayUtils.isEmpty(result)) {
            return new TeamInfoResultVO();
        }
        List<TeamEntOpenViewVO> entOpenViewVOList = new ArrayList<>();
        //设置参与人员用户名、电话和邮箱
        for (TeamEnterpriseViewVO ent : result) {
            TeamEntOpenViewVO entOpenViewVO = new TeamEntOpenViewVO();
            entOpenViewVO.setEnterpriseName(ent.getEnterpriseName());
            entOpenViewVO.setEntRole(ent.getEntRole());
            entOpenViewVO.setMemberVOs(setMembersInfo(ent));
            entOpenViewVOList.add(entOpenViewVO);
        }
        TeamEntOpenViewVO[] teamResult = entOpenViewVOList.toArray(new TeamEntOpenViewVO[0]);
        sort(teamResult);
        resultVO.setTeamVOs(teamResult);
        return resultVO;
    }

    private void sort(TeamEntOpenViewVO[] result) {
        //按企业角色和企业名称首字母进行排序
        Arrays.sort(result, new Comparator<TeamEntOpenViewVO>() {
            @Override
            public int compare(TeamEntOpenViewVO o1, TeamEntOpenViewVO o2) {
                if (o1 == o2) {
                    return 0;
                }
                if (o1 == null) {
                    return 1;
                }
                if (o2 == null) {
                    return -1;
                }
                if (!o1.getEntRole().equals(o2.getEntRole())) {
                    return o1.getEntRole().compareTo(o2.getEntRole());
                }
                return ChineseStringUtils.compareInDict(o1.getEnterpriseName(), o2.getEnterpriseName());
            }
        });
    }

    /**
     * 设置当前企业下成员的名称、手机和邮箱
     *
     * @param teamEnterpriseViewVO
     */
    private TeamMemOpenViewVO[] setMembersInfo(TeamEnterpriseViewVO teamEnterpriseViewVO) {
        TeamMemberViewVO[] members = teamEnterpriseViewVO.getTeamMemberViewVOs();
        if (ArrayUtils.isEmpty(members))
            return new TeamMemOpenViewVO[0];
         Map<String, TeamMemberViewVO> memberViewVOMap = new HashMap<String, TeamMemberViewVO>();
         int i = 0;
         for (i = 0; i < members.length; i++) {
                memberViewVOMap.put(members[i].getPkUser(), members[i]);
         }
         UserInfo[] users = userInfoQuery.queryUsers(memberViewVOMap.keySet().toArray(new String[0]));
         List<TeamMemOpenViewVO> teamMemOpenViewVOList = new ArrayList<>();
          if (!ArrayUtils.isEmpty(users)) {
                for (TeamMemberViewVO teamMemberViewVO : members) {
                    TeamMemOpenViewVO teamMemOpenViewVO = new TeamMemOpenViewVO();
                    teamMemOpenViewVO.setUserRole(teamMemberViewVO.getUserRole());
                    for (UserInfo userInfo : users) {
                        if (teamMemberViewVO.getPkUser().equals(userInfo.getUserId())) {
                            teamMemOpenViewVO.setUserName(userInfo.getUserName());
                            teamMemOpenViewVO.setPhoneNo(userInfo.getUserMobile());
                            teamMemOpenViewVO.setEmail(userInfo.getUserEmail());
                            break;
                        }
                    }
                    teamMemOpenViewVOList.add(teamMemOpenViewVO);
                }
          }
            return teamMemOpenViewVOList.toArray(new TeamMemOpenViewVO[0]);
    }
}
@Data
class TeamInfoResultVO{
    private String pkProject;
    private String pkTenant;
    private TeamEntOpenViewVO[] teamVOs;
}

@Data
class TeamEntOpenViewVO{
    private String enterpriseName;
    private Byte entRole;

    private TeamMemOpenViewVO[] memberVOs;
}
@Data
class TeamMemOpenViewVO {
    private String userName;
    private String phoneNo;
    private String email;
    private Byte userRole;
}

@Data
class TeamInfoRequestParam implements Serializable{
    private String pkTenant;
    private String pkProject;
}
